import { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import { useDispatch } from 'react-redux'
import useGetUserInfo from './useGetUserInfo'
import { getUserInfoService } from '../services/user'
import { loginReducer } from '../store/userReducer'

function useLoadUserData() {
  const [waitingUserData, setWaitingUserData] = useState(true)
  const dispatch = useDispatch()
  // ajax加载用户数据
  const { run } = useRequest(getUserInfoService, {
    manual: true,
    onSuccess: (result) => {
      const { username, nickname } = result
      // 存储到redux
      dispatch(loginReducer({username, nickname}))
    },
    onFinally: () => {
      setWaitingUserData(false)
    }
  })

  // 判断当前store里是否有用户信息
  const { username } = useGetUserInfo()
  useEffect(() => {
    if (username) { // 有就不重新加载了
      setWaitingUserData(false)
      return
    }
    run() // 没有就请求
  }, [username])

  return {waitingUserData}
}
export default useLoadUserData